import { Data } from "../../data/define";
import { getPath } from "./getPath";
import { getURLSearchParams } from "./getURLSearchParams";
import { transCellToObj } from "./transCellToObj";

export async function getDataFromAPI({ request }: Data, defineRequest: any) {
    const path = getPath(request, defineRequest);
    let body = null;
    let headers = new Headers();
    setToMapLike(headers, transCellToObj(request.headers));
    if (request.methods === "post") {
        switch (request.bodyType) {
            case "urlencoded":
                body = getURLSearchParams(transCellToObj(request.body!));
            case "form":
                body = createForm(transCellToObj(request.body)!);
            default:
                body = JSON.stringify(transCellToObj(request.body!));
                headers.set("content-type", "application/json");
        }
    }

    const result = await fetch(path, {
        method: request.methods,
        headers,
        body,
    })
        .then((res): Promise<Blob> => {
            return res.blob();
        })
        .catch(() => null);
    return [path, result] as [string, Blob | null];
}

const setToMapLike = <T extends { set(key: string, value: any): void }>(
    instance: T,
    obj: any
) => {
    if (obj)
        Object.entries(obj).forEach(([key, value]) => {
            instance.set(key, value);
        });
};
const createForm = (obj: any) => {
    const form = new FormData();
    Object.entries(obj).forEach(([key, value]) => {
        form.append(key, value as string | Blob);
    });
    return form;
};
